const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
const schedule = require('node-schedule');
app.use(cors());

// 解析token的中间件
const {expressjwt} = require('express-jwt');
const config = require('./config');
app.use(expressjwt({
	secret: config.jwtSecretKey,
	algorithms: ['HS256']
}).unless({path: [/^\/api|img|pdf/]}));

// 配置静态资源，通过域名可访问
app.use(express.static('./static'));
const fs = require('fs');
// 这段没用了
// app.get('/', (req, res) => {
//     fs.readFile('./static/index.html', (err, data) => {
//         if(err){
//             return res.status(404).send('404 Not Found.')
//         } else {
//             res.send(data)
//         }
//     })
// })

// 配置解析 appkication/x-www-form-urlencoded 格式的表单数据中间件
// app.use(express.urlencoded({extended: false}));

// 配置解析 json 数据的中间件
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// 请求头
app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    req.method === 'OPTIONS' ? res.send('CURRENT SERVICES SUPPORT CROSS DOMAIN REQUESTS!') : next();
});

// 封装发送函数
app.use((req, res, next) => {
	res.cc = function(err, status = 1){
		res.send({
			status,
			message: err instanceof Error ? err.message : err
		})
	},
	next()
});

// 登录模块
const loginRouter = require('./router/login');
app.use('/api', loginRouter);

// 部门模块
const departmentRouter = require('./router/department');
app.use('/my', departmentRouter);

// 岗位模块
const positionRouter = require('./router/position');
app.use('/my', positionRouter);

// 用户模块
const userRouter = require('./router/user');
app.use('/my', userRouter);

// 考勤模块
// 每天凌晨12点执行 // '0 7 9 5 9 *'
const attendance = require('./encapsulation/business/attendance/01addAttendanceSheet')
let rule = new schedule.RecurrenceRule();
rule.hour = 0;
rule.minute = 1;
rule.second = 0;
schedule.scheduleJob( '0 25 9 31 1 *', function(){
	console.log('更新了')
	attendance.addAttendanceSheet();
});
// 考勤路由
const attendanceRouter = require('./router/attendance');
app.use('/my', attendanceRouter);

// 项目路由
const projectRouter = require('./router/project');
app.use('/my', projectRouter);

// 投票路由
const voteRouter = require('./router/vote');
app.use('/my', voteRouter);

// 数据可视化
const dataRouter = require('./router/data');
app.use('/my', dataRouter);

// 权限模块
const activityRouter = require('./router/activity');
app.use('/my', activityRouter);

// 服务启动端口
app.listen(config.PORT, function() {
	console.log(`服务启动成功，地址为：${config.HOST}:${config.PORT}`)
})